﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Configuration.Provider;
using Formsy.Common;
using System.Text;
using System.Net.Mail;
using System.Web.Configuration;
using System.Net.Configuration;


namespace Formsy.Providers.Email
{
    public abstract class EmailProvider : ProviderBase
    {
        public virtual void Send(string formName, string senderAddress, string recipientAddresses, Dictionary<string, string> dictionary)
        {
            Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration("~\\Web.config");
            MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
            if (mailSettings == null)
                throw new Exception("Could not get mail settings from web.config");

            // parse recipients
            string[] recipients = recipientAddresses.Split(",".ToCharArray());

            // get values
            string emailBody = GetValuesForEmail(dictionary);
            
            // create smtp
            SmtpClient smtp = new SmtpClient(mailSettings.Smtp.Network.Host, mailSettings.Smtp.Network.Port);

            foreach (var r in recipients)
            {
                // create message and send
                MailMessage m = new MailMessage(new MailAddress(senderAddress), new MailAddress(r));
                m.Subject = formName;
                m.Body = emailBody;
                smtp.Send(m);
            }
        }



        /// <summary>
        /// Returns the dictionary as a string.
        /// Dictionary items are "\n" delimited.
        /// Key-value pairs are ":" delimited. 
        /// </summary>
        /// <param name="dictionary"></param>
        /// <returns></returns>
        public string GetValuesForEmail(Dictionary<string, string> dictionary)
        {
            // get key value pairs
            StringBuilder s = new StringBuilder();
            foreach (var key in dictionary.Keys)
            {
                s.Append(key);
                s.Append(": ");
                s.Append(dictionary[key]);
                s.Append("\n");
            }

            return s.ToString();
        }
    
    }


    public class EmailProviderCollection : ProviderCollection
    {
        // Return an instance of DataProvider
        // for a specified provider name
        new public EmailProvider this[string name]
        {
            get { return (EmailProvider)base[name]; }
        }
    }
}

